#!/bin/sh /etc/rc.common
#
#SFE connection manager has a lower priority, it should be started after other connection manager
#to detect the existence of connection manager with higher priority

START=72

have_cm() {
	if [ -d "/sys/kernel/debug/ecm" ]; then
		echo 1
	else
		echo 0
	fi
}

#load shortcut-fe connection manager
load_sfe_cm() {
	local kernel_version=$(uname -r)

	#shortcut-fe-drv.ko is not needed because other connection manager is not enabled
	if [ -d /sys/module/shortcut_fe_drv ]; then
		rmmod shortcut_fe_drv
	fi

	if [ -e /lib/modules/$kernel_version/shortcut-fe-cm.ko ] && [ ! -d /sys/module/shortcut_fe_cm ]; then
		insmod /lib/modules/$kernel_version/shortcut-fe-cm.ko && return
	fi 

	if [ -e /lib/modules/$kernel_version/fast-classifier.ko ] && [ ! -d /sys/module/fast_classifier ]; then
		insmod /lib/modules/$kernel_version/fast-classifier.ko && return
	fi
}

start() {
	local enabled
	local bridge
	local ipv6
	local sfe_ipv6

	enabled=$(uci -q get sfe.config.enabled)
	if [ "$enabled" -eq 1 ]; then
		if [ "$(have_cm)" -ne 1 ]; then
			load_sfe_cm
		fi
		bridge=$(uci -q get sfe.config.bridge)
		if [ -n "$bridge" ]; then
			echo "$bridge" > /sys/fast_classifier/skip_to_bridge_ingress
		fi
		ipv6=$(uci -q get sfe.config.ipv6)
		if [ $ipv6 -eq 1 ]; then
			sfe_ipv6=$(cat /sys/sfe_ipv6/debug_dev)
			if [ ! -f /dev/sfe_ipv6 ]; then
				mknod /dev/sfe_ipv6 c $sfe_ipv6 0
			fi
		else
			rm -f /dev/sfe_ipv6
		fi
	fi
}

stop() {
	if [ -d /sys/module/shortcut_fe_cm ]; then
		rmmod shortcut_fe_cm
	fi

	if [ -d /sys/module/fast_classifier ]; then
		rmmod fast_classifier
	fi
}

restart() {
	stop
	start
}
